package com.zhentao.filter;

import com.zhentao.config.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
@Order(-1)
public class AdUserFilter implements GlobalFilter, Ordered {


    // 匿名可访问的 url，网关过滤器其他代码省略
    private static final List<String> ANONYMOUS_URI_LIST = new ArrayList<>();

    static {
        // 注意：生产环境下面这两个要注释掉，或者用开启停用状态来确保接口文档是否可匿名访问。
        ANONYMOUS_URI_LIST.add("/api/product/doc.html");
        ANONYMOUS_URI_LIST.add("/api/product/v2/api-docs");
        ANONYMOUS_URI_LIST.add("/product/api/product/index");
        ANONYMOUS_URI_LIST.add("/api/order/cart/auth/addToCart");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String url = request.getURI().getPath();
        System.out.println(url);
        if (url.contains("product") || ANONYMOUS_URI_LIST.contains(url)){
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");

        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == 1 || i == 2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            ServerHttpRequest build = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", claimsBody.get("id").toString());
            }).build();
            exchange.mutate().request(build ).build();
        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();
        };

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
